<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/10
 * Time: 8:57
 */

namespace common\business\mdm;


use common\business\CommonHelper;
use common\business\db\MdmDeptDbCurd;
use common\consts\CommonResources;
use common\consts\Consts;
use common\consts\MdmConsts;
use common\helpers\StringUtil;
use common\models\Log;
use common\models\mdm\MdmDept;
use common\result\ActionResult;
use yii\helpers\Json;
use Yii;

class MdmDeptCrud extends MdmCrud
{
    /**
     * @param $obj MdmDept
     * @param $log Log
     * @return ActionResult
     */
    public function updateWithLog($obj, $log){
        return $this->createOrUpdate('Update', $obj, $log);
    }

    /**
     * @param $obj MdmDept
     * @return ActionResult
     */
    public function create($obj)
    {
        return $this->createOrUpdate('Create', $obj);
    }
    /**
     * @param $obj MdmDept
     * @return ActionResult
     */
    public function update($obj)
    {
        return $this->createOrUpdate('Update', $obj);
    }

    /**
     * @param $action string
     * @param $obj MdmDept
     * @param $log Log
     * @return ActionResult
     */
    protected function createOrUpdate($action, $obj, $log = null)
    {
        $modelClass = Yii::t('app', get_class($obj));
        if (!$obj){
            return new ActionResult(false, CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON($action, $modelClass, CommonHelper::getPrintName($obj), 'Obj is null'));
        }
        $api = new MdmApiHandler();
        $sResult = $api->syncMdmDept($obj);
        if (!$log){
            $log = new Log();
            $log->action = CommonResources::ACTION_NAME_MSG($action, $modelClass, CommonHelper::getPrintName($obj));
            $log->new_content = StringUtil::getShortString(Json::encode($obj->attributes), Consts::MAX_STRING_LENGTH);
        }
        $this->persistLog($log);
        return $sResult;
    }

    /**
     * @param $obj MdmDept
     * @return ActionResult
     */
    public function delete($obj)
    {
        $dbCrud = new MdmDeptDbCurd();
        return $dbCrud->delete($obj);
    }

    /**
     * @param $id integer
     * @return MdmDept
     */
    public function read($id)
    {
        return MdmDept::findOne(['PK_DEPARTMENT' => $id]);
    }
}